﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using System.Security.Permissions;
using Slam.FieldTypes;
using Slam.SharePoint;
using Slam.Events;
using Slam;

namespace SlamCms.SharePoint.Publishing.CustomActions
{
	[ToolboxData("<{0}:SubmitForApprovalButton runat=\"server\" />")]
	public class SubmitForApprovalButton : SaveButton
	{
		public SubmitForApprovalButton()
		{
			this.ControlMode = SPControlMode.Edit;
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
			//Slam.SlamContext.Get(List).Actions.Register(SlamEvent.PreSave, 10, listItem => SetSubmitForApproval());
			//Slam.SlamContext.Get(List).Actions.Register(SlamEvent.PostSave, 10, listItem => ResetSubmitForApproval());
		}

		protected override bool SaveItem()
		{
			if (base.List.EnableModeration)
			{
				ListItem.SetSlamProperty("SubmitItemForApproval", true);
			}
			bool success = base.SaveItem();

			return success;
		}

		protected void SetSubmitForApproval()
		{
			if (Page.Request.Params["__EVENTTARGET"].Contains("submitForApprovalButton") && base.List.EnableModeration)
			{
				ListItem.SetSlamProperty("SubmitItemForApproval", true);
			}
		}

		protected void ResetSubmitForApproval()
		{
			if (Page.Request.Params["__EVENTTARGET"].Contains("submitForApprovalButton") && base.List.EnableModeration)
			{
				SPListItem listItem = SPContext.Current.List.GetItemById(SPContext.Current.ListItem.ID);
				listItem.SetSlamProperty("SubmitItemForApproval", false);
				EventUtility eventUtility = new EventUtility();
				eventUtility.DisableEventHandlers();
				listItem.SystemUpdate(false);
				eventUtility.EnableEventHandlers();
			}
		}

		protected override string DefaultTemplateName
		{
			get
			{
				return "SlamCMSSubmitForApprovalButton";
			}
		}

		public override bool Visible
		{
			[SharePointPermission(SecurityAction.Demand, ObjectModel = true)]
			get
			{
				bool visible = false;
				if (base.List != null)
				{
					if (base.List.EnableModeration)
					{
						visible = base.Visible;

						if (!base.List.DoesUserHavePermissions(SPBasePermissions.EditListItems))
						{
							if (this.Controls[0].Controls[0] is Button)
							{
								(this.Controls[0].Controls[0] as Button).Enabled = false;
							}
							else if (this.Controls[0].Controls[1] is Button)
							{
								(this.Controls[0].Controls[1] as Button).Enabled = false;
							}
						}
					}
				}
				return visible;
			}

			[SharePointPermission(SecurityAction.Demand, ObjectModel = true)]
			set
			{
				base.Visible = value;
			}
		}
	}
}
